//
//  MAHomeWorkEditFinish.m
//  meiang_edu
//
//  Created by gong on 2018/9/13.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAHomeWorkEditFinishVC.h"
#import "MAHomeWorkEditFinishView.h"
#import <MapKit/MapKit.h>


@interface MAHomeWorkEditFinishVC ()<MAHomeWorkEditFinishViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,CLLocationManagerDelegate>

@property(nonatomic,strong)MAHomeWorkEditFinishView *finishView;
@property (strong,nonatomic) CLLocationManager* locationManager;


@property(nonatomic,strong)UITextField *titL;
@property(nonatomic,strong)UIView *imgBG;
@property(nonatomic,strong)  UIView *bgTopview;
@property(nonatomic,strong)UILabel *addressL;

@property(nonatomic,strong)  UIView *contentBgView;
@property(nonatomic,strong)UITextField *contentF;
@property(nonatomic,strong)UIImageView *imgV;
@property(nonatomic,strong)UIView *dingweiView;
@property(nonatomic,strong)UIScrollView *mianScrollView;
@property(nonatomic,assign)int flag;
@property(nonatomic,copy)NSString *clocation;

@end

@implementation MAHomeWorkEditFinishVC

- (instancetype)initWithFlag:(int )flag {
    self = [super init];
    if (self) {
        self.flag = flag;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.title=@"通用录入";
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"savebutton_logo"] style:UIBarButtonItemStylePlain target:self action:@selector(saveClick)];

    [self makeUI];
    
    /** 初始化collectionView */
    [self initPickerView];
}

- (void)makeUI {
    
//    MAHomeWorkEditFinishView *view=[[MAHomeWorkEditFinishView alloc]initWithFrame:self.view.bounds];
//    [self.view addSubview:view];
//    view.delegate=self;
//    self.finishView = view;

    
    UIScrollView *scroll=[[UIScrollView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:scroll];
    scroll.backgroundColor=ViewBgColor;
    
    UIView *bgTopview = [[UIView alloc]initWithFrame:CGRectMake(4, 4, SCREEN_WIDTH-8, 50)];
    [scroll addSubview:bgTopview];
    bgTopview.backgroundColor=[UIColor whiteColor];
    bgTopview.layer.masksToBounds=YES;
    bgTopview.layer.cornerRadius=5;
    _bgTopview=bgTopview;
    
    
    _titL=[[UITextField alloc]initWithFrame:CGRectMake(6, 0, bgTopview.width-12, bgTopview.height)];
    _titL.font=[UIFont systemFontOfSize:FONT_SIZE_14];
    _titL.textColor=[UIColor colorWithHexString:@"666666"];
    _titL.placeholder=@"请在此输入标题";
    [bgTopview addSubview:_titL];
    _titL.delegate=self;
    
    CGFloat Y = _bgTopview.bottom+4;
    if (self.flag == 1) {
        Y = 4;
        bgTopview.hidden=YES;
    }
    
    UIView *contentBgView = [[UIView alloc]initWithFrame:CGRectMake(4, Y, SCREEN_WIDTH-8, 50)];
    [scroll addSubview:contentBgView];
    contentBgView.backgroundColor=[UIColor whiteColor];
    contentBgView.layer.masksToBounds=YES;
    contentBgView.layer.cornerRadius=5;
    self.contentBgView = contentBgView;
    
    _contentF=[[UITextField alloc]initWithFrame:CGRectMake(6, 0, bgTopview.width-12, bgTopview.height)];
    _contentF.font=[UIFont systemFontOfSize:FONT_SIZE_14];
    _contentF.textColor=[UIColor colorWithHexString:@"666666"];
    _contentF.placeholder=@"请在此输入内容";
    [contentBgView addSubview:_contentF];
    
    UIView *dingweiBg=[[UIView alloc]initWithFrame:CGRectMake(_bgTopview.x, _imgBG.bottom+4, SCREEN_WIDTH-8, 50)];
    [scroll addSubview:dingweiBg];
    dingweiBg.backgroundColor=[UIColor whiteColor];
    dingweiBg.layer.masksToBounds=YES;
    dingweiBg.layer.cornerRadius=5;
    self.dingweiView = dingweiBg;
    
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(12, 0, 40, 50)];
    [dingweiBg addSubview:lab];
    lab.font=[UIFont systemFontOfSize:14];
    lab.text=@"定位";
    lab.textColor=[UIColor colorWithHexString:@"666666"];
    
    UILabel *addrL=[[UILabel alloc]initWithFrame:CGRectMake(65, 0, SCREEN_WIDTH-8-12-65, 50)];
    [dingweiBg addSubview:addrL];
    addrL.textColor=[UIColor colorWithHexString:@"999999"];
    addrL.font=[UIFont systemFontOfSize:14];
    addrL.textAlignment=NSTextAlignmentRight;
    addrL.text=@"定位请点击";

    _addressL=addrL;
    addrL.userInteractionEnabled=YES;
    UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startLocation)];
    [addrL addGestureRecognizer:ges];
    
    [self updateViewsFrame];
}

/**
 *  界面布局 frame
 */
- (void)updateViewsFrame{
    
    //photoPicker
    [self updatePickerViewFrameY:self.contentBgView.bottom+4+self.contentBgView.height+20];
    
    self.dingweiView.frame = CGRectMake(4, [self getPickerViewFrame].origin.y+[self getPickerViewFrame].size.height-50, _bgTopview.width, 50);
    
   CGFloat allViewHeight = self.dingweiView.frame.origin.y+self.dingweiView.frame.size.height+10;
    
    _mianScrollView.contentSize = self.mianScrollView.contentSize = CGSizeMake(0,allViewHeight);
}

- (void)pickerViewFrameChanged{
    [self updateViewsFrame];
}

-(void)saveClick
{
    if (self.contentF.text.length == 0) {
        [MBManager showBriefAlert:@"请输入内容"];
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确认完成本次编辑?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==1) {
        
        [self saveInput];
    }
}

-(void)saveInput{
    
    if (self.contentF.text.length == 0) {
        [MBManager showBriefAlert:@"请输入内容"];
        return;
    }
    if (self.imageArray.count) {
        [self uploadImg:self.imageArray];
    }
    else
    {
        [self saveInfoWithImage_list:@"0" imgCount:@"0"];
    }
}


-(void)uploadImg:(NSMutableArray *)imageArr{
    [[ZOSSFileUploader shareInstance]  asyncUploadImages:[self getBigImageArray] progress:^(int64_t byteSent, int64_t bytesTotal, double progress) {
        //        NSLog(@" %lld, %lld, --%lf",byteSent, bytesTotal,progress);
    } complete:^(NSArray<NSString *> *names, BOOL isSuccess) {
        NSLog(@"%@",names);
        NSLog(@" IS success ----%d---",isSuccess);
        NSLog(@"-----");
        NSMutableArray *arr =[NSMutableArray array];
        for (NSString* name in names) {
            NSString* fullStr = [ZOSSFileUploader aliUrlWithName:name];
            NSLog(@"%@",fullStr);
            
            NSString * fileName;//文件名
            NSRange range = [name rangeOfString:@"." options:NSBackwardsSearch];
            if (range.length>0){
                fileName=[name substringToIndex:NSMaxRange(range)];
            }
            fileName= [fileName stringByReplacingOccurrencesOfString:@"." withString:@""];
            [arr addObject:fileName];
        }
        NSString *image_list = [arr componentsJoinedByString:@","];
        [self saveInfoWithImage_list:image_list imgCount:[NSString stringWithFormat:@"%lu",(unsigned long)names.count]];
        
    }];
    
}

-(void)saveInfoWithImage_list:(NSString *)image_list imgCount:(NSString *)image_count
{
    if (self.clocation.length == 0 || !self.clocation)
    {
        self.clocation = @"";
    }
    if (_titL.text.length == 0 || !_titL.text)
    {
        _titL.text = @"";
    }
    
    //为了适配z发送专属服务
    if (![self.giscene isEqualToString:@"organization_personal"] || ![self.giscene isEqualToString:@"    organization_notice_leave"])
    {
        if (self.or_id.length == 0 || !self.or_id)
        {
            [MBManager showBriefAlert:@"机构id不能为空"];
            return;
        }
    }
   
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    NSDictionary *param;
    if ([self.giscene isEqualToString:@"organization_personal"] || [self.giscene isEqualToString:@"organization_notice_leave"])
    {
        param = @{
                  @"us_idinput": userinfo.ID, //录入人ID
                  @"image_count": image_count, //图片数量
                  @"ch_id": @"", //学生id
                  @"image_list": image_list,//图片guid 多个用，隔开
                  @"clocation": self.clocation,//地理位置坐标
                  @"ph_id": @"", //相册ID
                  @"cnotes": _contentF.text,//说明备注 作业多条用数组
                  @"iscope": @"",//接收范围
                  @"ccaption": @"",//标题
                  @"or_id": self.or_id,//机构ID //当前消息发送者的ID
                  @"clocationname": self.addressL.text,//地理位置
                  @"parent_cid":@"", //是当前消息的ID
                  @"giscene":self.giscene//场景code // 详情中的message_type
                  };
    }
    else
    {
        param = @{
                  @"us_idinput": userinfo.ID, //录入人ID
                  @"image_count": image_count, //图片数量
                  @"ch_id": @"", //学生id
                  @"image_list": image_list,//图片guid 多个用，隔开
                  @"clocation": self.clocation,//地理位置坐标
                  @"ph_id": @"", //相册ID
                  @"cnotes": _contentF.text,//说明备注 作业多条用数组
                  @"iscope": @"",//接收范围
                  @"ccaption": @"",//标题
                  @"or_id": self.or_id,//机构ID //当前消息发送者的ID
                  @"clocationname": self.addressL.text,//地理位置
                  @"giscene": @"11",  //场景code // 详情中的message_type
                  @"parent_cid":self.keyid, //是当前消息的ID
                  };
    }
    
    [MBManager showLoading];
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@", SavePutInfo_url, userinfo.ID] parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:userinfo.token forHTTPHeaderField:@"token"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                self.navigationItem.rightBarButtonItem = nil;
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}


//开始定位

-(void)startLocation{
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [_locationManager requestWhenInUseAuthorization];
            }
            break;
        case kCLAuthorizationStatusDenied:
        {
            
        }
        default:
            break;
    }
    
}



- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *newLocation = locations[0];
    
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    self.clocation = [NSString stringWithFormat:@"%f,%f",oldCoordinate.latitude,oldCoordinate.longitude];
    
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
        
        for (CLPlacemark *place in placemarks) {
            
            NSLog(@"name,%@",place.name);                      // 位置名
            NSLog(@"thoroughfare,%@",place.thoroughfare);      // 街道
            NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
            NSLog(@"locality,%@",place.locality);              // 市
            NSLog(@"subLocality,%@",place.subLocality);        // 区
            NSLog(@"country,%@",place.country);                // 国家
            //            place.administrativeArea 省
            self.addressL.text = [NSString stringWithFormat:@"%@%@%@%@%@",place.country,place.administrativeArea,place.locality,place.subLocality,place.thoroughfare];
        }
    }];
}
@end
